package com.dwy2002.order.impl;

import cn.hutool.core.bean.BeanUtil;
import com.aliyun.oss.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dwy2002.common.utils.RedisUtils;
import com.dwy2002.order.mapper.OrderProductMapper;
import com.dwy2002.order.service.IOrderProductService;
import com.dwy2002.pojo.dto.order.OrderProductDTO;
import com.dwy2002.pojo.po.order.OrderProduct;
import com.dwy2002.pojo.po.product.Products;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.dwy2002.common.utils.Utils.validateIdNotEmpty;
import static com.dwy2002.enums.rabbit.ProductRabbitConstants.*;

/**
 * @author 杜伟毅
 * @version 1.0
 * @since 2025/03/06
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderProductServiceImpl extends ServiceImpl<OrderProductMapper, OrderProduct> implements IOrderProductService {
    private final RabbitTemplate rabbitTemplate;
    private final RedisUtils redisUtils;

    /**
     * 添加订单商品明细
     *
     * @param orderId 订单ID
     * @param dtos    订单商品明细DTO
     * @author 杜伟毅
     * @since 2025/3/9 0009 16:21
     */
    @Override
    public void saveOrderProduct(String orderId, List<OrderProductDTO> dtos) {
        validateIdNotEmpty(orderId, "saveOrderProduct");
        List<OrderProduct> orderProducts = BeanUtil.copyToList(dtos, OrderProduct.class);
        orderProducts.parallelStream().forEach(orderProduct -> {
            orderProduct.setOrderId(orderId);
            save(orderProduct);
        });
    }

    /**
     * 查询商品信息
     *
     * @param orderId 订单ID
     * @return 返回商品集合
     * @author 杜伟毅
     * @since 2025/3/12 0012 20:00
     */
    @Override
    public List<Products> getProductsByOrderId(String orderId) {
        validateIdNotEmpty(orderId, "getProductsByOrderId");
        //查询商品id集合
        LambdaQueryWrapper<OrderProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderProduct::getOrderId, orderId);
        List<OrderProduct> orderProducts = list(lqw);
        List<String> productIds = orderProducts.stream().map(OrderProduct::getProductId).toList();

        // 发送响应到 ReplyTo 队列
        rabbitTemplate.convertAndSend(
                PRODUCT_REQUEST_EXCHANGE, // 使用响应专属交换机
                PRODUCT_REQUEST_ROUTING_KEY, // 响应路由键
                productIds,
                message -> {
                    message.getMessageProperties().setReplyTo(PRODUCT_RESPONSE_QUEUE);
                    message.getMessageProperties().setCorrelationId(orderId);
                    return message;
                });

        // 注册回调监听器
        rabbitTemplate.setReplyTimeout(30000); // 30秒超时
        try {
            return rabbitTemplate.receiveAndConvert(PRODUCT_RESPONSE_QUEUE, new ParameterizedTypeReference<>() {
            });
        } catch (AmqpException e) {
            throw new ServiceException("数据响应超时");
        }
    }

    /**
     * 删除OrderProduct信息
     *
     * @param orderId 订单ID
     * @author 杜伟毅
     * @since 2025/3/12 0012 19:36
     */
    @Override
    public void deleteOrderProduct(String orderId) {
        validateIdNotEmpty(orderId, "deleteOrderProduct");
        LambdaQueryWrapper<OrderProduct> lqw = new LambdaQueryWrapper<>();
        lqw.eq(OrderProduct::getOrderId, orderId);
        remove(lqw);
    }


}
